const db = require('../db/mysql/mysql');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const {secret,server} = require('../config/server.json');
let uuid = require('node-uuid');
module.exports = {
    login:async function(account,password){
        let user_query_sql = 'select * from user where account = ?';
        let user_query_args = [account];
        let user =  await db.query(user_query_sql,user_query_args);
        if(!user){
            return {
                code:-1
            }
        };
        if(user && user instanceof Array && user.length == 0){
            return {
                code:-1
            }
        };
        user = user[0];
        console.log('user=====?。》',user);
        let boolean = bcrypt.compareSync(password,user.password);
        if(!boolean){
            return {
                code:-1
            };
        };
        let token = jwt.sign({
            unid:user.unid,
        },secret);
        return {
            token,
            server
        };
    },
    register:async function(account,passwrod,ip){
        try {
            let user_query_sql = 'select * from user where account = ? ';
            let user_query_args = [account];
            let user = await db.query(user_query_sql,user_query_args);
            if(user && user instanceof Array && user.length > 0){
                return {
                    code:-1
                }
            };
            let salt = bcrypt.genSaltSync(10);
            const hash = bcrypt.hashSync(passwrod, salt);
            let time = new Date().toJSON().slice(0, 19).replace('T', ' ');
            let role_sql = 'select max(uid) from role';
            let maxUid = await db.query(role_sql,[]);
            if(user && user instanceof Array && user.length > 0){
                if(maxUid[0]){
                    maxUid = maxUid[0];
                }
            }else
            {
                maxUid = 100000;
            }
            maxUid ++;
            console.log('maxUid====>',maxUid);
            let unid = uuid.v1();
            let user_insert_sql = "insert into user (account,password,last_login_time,last_login_ip,created_at,updated_at,status,unid) values ( ?,?,?,?,?,?,?,?)";
            let user_insert_args = [account,hash,time,ip,time,time,1,unid];
            await db.query(user_insert_sql,user_insert_args);
            let role_insert_sql = "insert into role (userid,coin,diamond,gems,gameid,sex,name,created_at,updated_at,status,uid) values (?,?,?,?,?,?,?,?,?,?,?)";
            let role_insert_args = [unid,0,0,0,1000,1,account,time,time,1,maxUid];
            await db.query(role_insert_sql,role_insert_args);
        } catch (error) {
            return {
                code:-1,
                msg:'注册失败'+error.stack
            };
        };
        return {
            code:1001,
            msg:'注册成功'
        };
    }
}